package com.nelson.encrypt;

import com.android.build.gradle.AppExtension;
import com.android.build.gradle.api.ApplicationVariant;
import com.android.build.gradle.api.BaseVariantOutput;
import com.nelson.encrypt.bean.PluginParams;
import com.nelson.encrypt.task.EncryptTask;
import com.nelson.encrypt.utils.LogUtils;

import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import java.io.File;

/**
 * <pre>
 *   @author :   李磊
 *   time    :   2021/10/10
 *   des     :
 * </pre>
 */
public class EncryptPlugin implements Plugin<Project> {
    @Override
    public void apply(Project project) {
        System.out.println("========================");
        System.out.println("Encrypt Plugin Started");
        System.out.println("========================");

        // 增加插件参数配置
        project.getExtensions().create("EncryptPluginParams", PluginParams.class);

        // 注册监听，解析build gradle后会被执行
        project.afterEvaluate(new Action<Project>() {
            @Override
            public void execute(Project project) {
                // 获取配置的参数
                System.out.println("Parsing params");

                // 打印配置信息
                PluginParams pluginParams = project.getExtensions().getByType(PluginParams.class);
                if (pluginParams.isDebug()) {
                    LogUtils.enableDebug();
                }
                LogUtils.i(pluginParams.toString());

                // 获取动态生成的apk文件
                AppExtension appExtension = project.getExtensions().getByType(AppExtension.class);

                // 得到一个集合【Debug，Release】
                appExtension.getApplicationVariants().all(new Action<ApplicationVariant>() {
                    @Override
                    public void execute(ApplicationVariant applicationVariant) {

                        // 获取变体的打包输出位置
                        applicationVariant.getOutputs().all(new Action<BaseVariantOutput>() {
                            @Override
                            public void execute(BaseVariantOutput variantOutput) {
                                // apk 文件
                                File outputFile = variantOutput.getOutputFile();

                                // release / debug
                                String name = variantOutput.getName();

                                // 针对不同的变体创建加固任务
                                project.getTasks().register("Encrypt" + name, EncryptTask.class, outputFile, pluginParams);
                            }
                        });
                    }
                });
            }
        });
    }
}
